

package com.lzy.mall.common.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lzy.mall.common.exception.IErrorCode;
import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class ResultUtils<T> extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;


	public ResultUtils() {
		put("code", 0);
		put("msg", "success");
	}
	
	public static ResultUtils error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}
	
	public static ResultUtils error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	
	public static ResultUtils error(int code, String msg) {
		ResultUtils r = new ResultUtils();
		r.put("code", code);
		r.put("msg", msg);
		return r;
	}

	public static ResultUtils error(IErrorCode errorCode) {
		return error(errorCode.getCode(),errorCode.getMsg());
	}

	public static ResultUtils ok(String msg) {
		ResultUtils r = new ResultUtils();
		r.put("msg", msg);
		return r;
	}

	public static ResultUtils ok(Map<String, Object> map) {
		ResultUtils r = new ResultUtils();
		r.putAll(map);
		return r;
	}
	
	public static <T> ResultUtils<T> ok() {
		return new ResultUtils();
	}

	public static <T> ResultUtils<T> ok(T data) {
		ResultUtils resultUtils = new ResultUtils();
		resultUtils.put("data",data);
		return resultUtils;
	}

	public static <T> ResultUtils<T> ok(T data,String msg) {
		ResultUtils resultUtils = new ResultUtils();
		resultUtils.put("data",data);
		resultUtils.put("msg",msg);
		return resultUtils;
	}

	public ResultUtils put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	public ResultUtils setData(Object value) {
		super.put("data", value);
		return this;
	}

	public String getJson(String key){
		Object o = super.get(key);
		String jsonStr = JSONUtil.toJsonStr(o);
		return jsonStr;
	}


	public <T> T getBean(String key,Class<T> beanClass) {
		String json = getJson(key);
		return JSONUtil.toBean(json,beanClass);
	}

	public <T> T getBean(Class<T> beanClass) {
		String json = getJson("data");
		return JSONUtil.toBean(json,beanClass);
	}


	public Integer getCode() {
		return (Integer) this.get("code");
	}
}
